package com.oocl.servlet;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.exception.MyException;
import com.oocl.pojo.Customer;
import com.oocl.service.CustomerService;
import com.oocl.service.impl.CustomerServiceFactory;
import com.oocl.service.impl.ServiceFactory;

/**
 * Servlet implementation class UpdateDataServlet
 */
public class UpdateDataServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String idStr = request.getParameter("id");
		int id = Integer.parseInt(idStr);
		String username = request.getParameter("username");
		String salary = request.getParameter("salary");
		String birth = request.getParameter("birth");
		String sex = request.getParameter("sex");
		String[] favcs = request.getParameterValues("favcs");
		//check
		
		
		double sal = Double.parseDouble(salary);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date birthday = null;
		try {
			 birthday = df.parse(birth);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		boolean se = Boolean.parseBoolean(sex);
		
		
	    Customer c = new Customer();
	    c.setId(id);
		c.setUname(username);
		c.setBirth(birthday);
		c.setSalary(sal);
		c.setSex(se);
		int[] favcIds =new int[0];
		if(favcs!=null){
			favcIds = new int[favcs.length];
	     for(int i=0;i<favcs.length;i++){
		     favcIds[i] = Integer.parseInt(favcs[i]);
	       }
		}
		
		CustomerServiceFactory factory =null;
		try {
			factory = (CustomerServiceFactory) ServiceFactory.getServiceFactory(CustomerServiceFactory.CUSTOMER);
			CustomerService cSer = factory.getService();
			cSer.update(c,favcIds);
		} catch (MyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.sendRedirect("list");
		
	}

}
